<?php
/**
 * @table paysystems
 * @id 2pay4you
 * @title 2pay4you
 * @visible_link https://www.2pay4you.com
 * @recurring none
 * @am_payment_api 6.0
 */
class Am_Paysystem_2pay4you extends Am_Paysystem_Abstract
{
    const PLUGIN_STATUS = self::STATUS_DEV;
    const PLUGIN_REVISION = '6.3.32';

    const URL = "https://www.2pay4you.com/shopapi/ipn/";

    protected $defaultTitle = '2pay4you';
    protected $defaultDescription = '';

    function getSupportedCurrencies()
    {
        return ['USD','EUR'];
    }

    public function _initSetupForm(Am_Form_Setup $form)
    {
        $form->addText('public_key', ['size' => 20])->setLabel('Your Public Key');
        $form->addText('payment_key', ['size' => 20])->setLabel('Your Payment Key');
        $form->addSecretText('secret', ['size' => 20])->setLabel('Your Shop Api Password');
        $form->addAdvcheckbox('testing')->setLabel('Testing mode');
    }

    public function _process($invoice, $request, $result)
    {
        $a = new Am_Paysystem_Action_Form(self::URL);
        $a->public_key = $this->getConfig('public_key');
        $a->payment_key = $this->getConfig('payment_key');
        $a->product = $invoice->getLineDescription();
        $a->amount = $invoice->first_total;
        $a->currency = $invoice->currency;
        $a->qty = 1;
        $a->verifycode = md5($this->getConfig('secret')).md5($a->amount);
        $a->order_id = $invoice->public_id;
        $a->notify_url = $this->getPluginUrl('ipn');
        $a->return_url = $this->getReturnUrl();
        $a->cancel_url = $this->getCancelUrl();
        $a->test_mode = $this->getConfig('testing') ? 'ON' : 'OFF';
        $a->filterEmpty();
        $result->setAction($a);

    }

    public function createTransaction($request, $response, array $invokeArgs)
    {
        return new Am_Paysystem_Transaction_2pay4you($this, $request, $response, $invokeArgs);
    }

    public function getRecurringType()
    {
        return self::REPORTS_NOT_RECURRING;
    }

}

class Am_Paysystem_Transaction_2pay4you extends Am_Paysystem_Transaction_Incoming
{
    public function getUniqId()
    {
        return $this->request->get('txid');
    }

    public function validateSource()
    {
        return $this->request->get('hash') ==
            md5($this->request->get('txid') . ":" . md5($this->getPlugin()->getConfig('secret')) . ":" . $this->request->get('amount') . ":" . $this->request->get('public_key') . ":" . $this->request->get('payer'));
    }

    public function validateStatus()
    {
        return true;
    }

    public function validateTerms()
    {
        return doubleval($this->invoice->first_total) == doubleval($this->request->get('amount'));
    }

    public function findInvoiceId()
    {
        return $this->request->get('order_id');
    }
}
